import useLocale from '@/utils/useLocale';
import {
  Button,
  Modal,
  Select,
  Skeleton,
  Image,
  Empty,
} from '@arco-design/web-react';
import React, { useContext, useEffect, useState } from 'react';
import locale from './locale';
import styles from './style//index.module.less';
import cs from 'classnames';
import { GlobalContext } from '@/context';
import { IconDownload } from '@arco-design/web-react/icon';
import { DownloadInvestigation, investigations } from '@/api/modules/violation';
import { FileLink } from '@/api/modules';
import useIsMountedRef from '@/utils/useIsMountedRef';
import ModalTitle from '@/components/ModalTitle';

const Option = Select.Option;
// const { useForm } = Form;

const Attachments = ({ srcList }) => {
  const [fileList, setFileList] = useState([]);
  const t = useLocale(locale);

  const fetchData = async (url) => {
    const { data } = await FileLink({ objectKey: url, fileName: '' }, false);
    return data;
  };

  useEffect(() => {
    if (srcList && srcList.length > 0) {
      const fetchDataInOrder = async () => {
        const promises = srcList.map((url) => fetchData(url));
        const results = await Promise.all(promises);
        setFileList(results);
      };
      fetchDataInOrder();
    }
  }, []);

  return (
    <>
      <div className={styles['row']}>
        <div className={styles['col']}>
          <div className={styles['label']}>
            {t['investigationReport.witness.attachments']}
          </div>
          <div
            className={styles['value']}
            style={{
              display: 'flex',
              flexWrap: 'wrap',
            }}
          >
            <Image.PreviewGroup infinite>
              {fileList.map((src, index) => (
                <div
                  key={index}
                  style={{
                    marginBottom: '12px',
                    marginRight: '12px',
                    width: '80px',
                    height: '80px',
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    background: 'var(--investigationReport-bg)',
                    borderRadius: '4px',
                    overflow: 'hidden',
                  }}
                >
                  <Image src={src} width={80} alt={null} />
                </div>
              ))}
            </Image.PreviewGroup>
          </div>
        </div>
      </div>
    </>
  );
};

const Signtures = ({ signatures, mode = 0 }) => {
  const { lang } = useContext(GlobalContext);
  const enumRole = [
    {
      key: 'VIOLATOR',
      value: { en: 'Violator Signature', ar: 'توقيع المخالف' },
    },
    { key: 'WITNESS', value: { en: 'Witness Signature', ar: 'توقيع الشاهد' } },
    {
      key: 'SUSPECT',
      value: { en: 'Suspect Signature', ar: 'توقيع المشتبه به' },
    },
    {
      key: 'WHISTLEBLOWER',
      value: { en: 'Whistleblower Signature', ar: 'توقيع المبلغ' },
    },
  ];
  const signatureText = (key: string) => {
    return enumRole.find((item) => item.key === key)?.value[
      lang === 'en-US' ? 'en' : 'ar'
    ];
  };

  const [signList, setSignList] = useState([]);
  const t = useLocale(locale);
  const signaturesKey = {
    'Witness/Violator': t['investigationReport.witness.title'],
    writer: t['investigationReport.details.writer'],
    translator: t['investigationReport.details.translator'],
    investigator: t['investigationReport.details.investigator'],
    investigator_2: `${t['investigationReport.details.investigator']} 2`,
    investigator_3: `${t['investigationReport.details.investigator']} 3`,
  };
  useEffect(() => {
    if (signatures && signatures.length > 0) {
      const fetchDataInOrder = async () => {
        for (const item of signatures) {
          const { data } = await FileLink(
            { objectKey: item.value, fileName: '' },
            false
          );
          setSignList((a) => [
            ...a,
            {
              key:
                mode == 0 ? signaturesKey[item.key] : signatureText(item.key),
              value: data,
            },
          ]);
        }
      };
      fetchDataInOrder();
    }
  }, []);

  return (
    <>
      <div className={styles['row']}>
        <div className={styles['col']}>
          <div className={styles['label']}>
            {t['investigationReport.witness.signtures']}
          </div>
          <div
            className={cs(styles['value'], styles['signtures'])}
            style={{
              display: 'flex',
              flexWrap: 'wrap',
            }}
          >
            {signList.map((a) => (
              <div className={cs(styles['signtures-item'])} key={a.key}>
                <div style={{ padding: '6px 0' }}>
                  <Image src={a.value} width={120} alt={null} />
                </div>
                <span className={styles['text']}> {a.key}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </>
  );
};

function InvestigationReport({
  refNumber,
  visible,
  onVisible,
}: {
  refNumber: string;
  visible: boolean;
  onVisible: (e: boolean) => void;
}) {
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);
  const onCancel = () => {
    onVisible(false);
  };
  // const [enums, setEnums] = useState<{ [key: string]: EnumsRes[] }>({
  //   violatorOrWitnessEnums: [],
  // });
  // const getEnums = async () => {
  //   try {
  //     const enumData = await Promise.all([
  //       Enums({ type: 'ViolatorOrWitnessEnums' }),
  //     ]);
  //     if (isMountedRef.current) {
  //       setEnums({
  //         violatorOrWitnessEnums: enumData[0].data,
  //       });
  //     }
  //   } catch (e) {}
  // };

  const [list, setList] = useState([]);
  const [index, setIndex] = useState(undefined);
  const [details, setDetails] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const fetchData = () => {
    setLoading(true);
    investigations({ refNumber })
      .then((res) => {
        if (isMountedRef.current) {
          setLoading(false);

          const list = [...res.data];
          setList(list);
          const length = list.length;
          if (length > 0) {
            setIndex(0);
            setDetails(list[0]);
          }
        }
      })
      .catch(() => {
        setLoading(false);
      });
  };

  const onSelect = (e) => {
    setIndex(e);
    setDetails(list[e]);
  };

  const isMountedRef = useIsMountedRef();
  // const [form] = useForm();
  // useEffect(() => {
  //   // getEnums();
  //   form.setFieldsValue({
  //     hasReported: false,
  //   });
  // }, []);
  useEffect(() => {
    if (visible && refNumber) {
      fetchData();
    }
  }, [visible, refNumber]);

  const download = () => {
    const params = {
      refNumber: refNumber,
      type: 'pdf',
      // lang: lang === 'en-US' ? 'en' : 'ar',
      fileName: details.fileName,
    };
    // startDownload(params, 'en');
    startDownload(params, 'ar');
  };

  const startDownload = (params, lang) => {
    DownloadInvestigation({ ...params, lang }).then((res) => {
      const blob = new Blob([res]);
      const blobUrl = window.URL.createObjectURL(blob);
      const exportFile = document.createElement('a');
      exportFile.style.display = 'none';
      exportFile.download = `${params.refNumber}(${params.fileName} ${lang}).pdf`;
      exportFile.href = blobUrl;
      document.body.appendChild(exportFile);
      exportFile.click();
      document.body.removeChild(exportFile);
      window.URL.revokeObjectURL(blobUrl);
    });
  };

  return (
    <>
      <Modal
        escToExit={false}
        title={<ModalTitle title={t['investigationReport.title']} />}
        style={{ width: '870px' }}
        visible={visible}
        onCancel={() => onCancel()}
        maskClosable={true}
        unmountOnExit={true}
        footer={null}
        className={cs(styles['investigationReport'], rtl ? 'rtl' : '')}
      >
        <div
          className={cs(
            styles['investigationReport-info'],
            rtl ? styles['rtl'] : ''
          )}
        >
          <Skeleton
            loading={loading}
            style={{ width: '96%', margin: '20px auto' }}
            text={{ rows: 7 }}
            animation
          >
            <div className={cs(styles['investigationReport-header'])}>
              {list.length > 0 && (
                <>
                  <Select
                    placeholder={t['searchTable.select.placeholder']}
                    style={{ width: '220px' }}
                    onChange={onSelect}
                    value={index}
                  >
                    {list.map((option, index) => (
                      <Option key={index} value={index}>
                        {option.fileName}
                      </Option>
                    ))}
                  </Select>

                  {/* <Tooltip
                    position="bottom"
                    content={t['hover.ExportMasterReport']}
                  > */}
                  <Button
                    style={{ textAlign: 'center' }}
                    shape="circle"
                    type="primary"
                    icon={<IconDownload />}
                    onClick={download}
                  />
                  {/* </Tooltip> */}
                </>
              )}
            </div>
            <div className={styles['investigationReport-scroll']}>
              {list.length > 0 ? (
                <>
                  <div
                    className={styles['investigationReport-content']}
                    key={index}
                  >
                    {/* Investigation Details */}
                    <div className={styles['item']}>
                      <div className={styles['item-header']}>
                        {t['investigationReport.details.title']}
                      </div>
                      <div className={styles['item-content']}>
                        <div className={styles['row']}>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.referenceNo']}
                            </div>
                            <div className={styles['value']}>{refNumber}</div>
                          </div>
                        </div>
                        <div className={styles['row']}>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.location']}
                            </div>
                            <div className={styles['value']}>
                              {details?.location}
                            </div>
                          </div>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.date']}
                            </div>
                            <div className={styles['value']}>
                              {details?.investigationDate}
                            </div>
                          </div>
                        </div>
                        <div className={styles['row']}>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.writer']}
                            </div>
                            <div className={styles['value']}>
                              {details?.writer?.name}
                            </div>
                          </div>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.translator']}
                            </div>
                            <div className={styles['value']}>
                              {details?.translator || '--'}
                            </div>
                          </div>
                        </div>
                        <div className={styles['row']}>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.investigator']}
                            </div>
                            <div className={styles['value']}>
                              {details?.investigator?.name || '--'}
                            </div>
                          </div>
                          {
                            <div className={styles['col']}>
                              <div className={styles['label']}>
                                {t['investigationReport.details.investigator']}{' '}
                                {'    '}2
                              </div>
                              <div className={styles['value']}>
                                {details?.investigator_2?.name || '--'}
                              </div>
                            </div>
                          }
                        </div>
                        {
                          <div className={styles['row']}>
                            <div className={styles['col']}>
                              <div className={styles['label']}>
                                {t['investigationReport.details.investigator']}{' '}
                                {'    '}3
                              </div>
                              <div className={styles['value']}>
                                {details?.investigator_3?.name || '--'}
                              </div>
                            </div>
                          </div>
                        }

                        <div className={styles['row']}>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.details.caseSummary']}
                            </div>
                            <div className={styles['value']}>
                              {details?.caseSummary}
                            </div>
                          </div>
                        </div>
                        {details?.attachment &&
                          details?.attachment.length > 0 && (
                            <Attachments srcList={details.attachment} />
                          )}
                      </div>
                    </div>

                    {/* Witness / violator  */}
                    {details?.details &&
                      details?.details.map((a, index) => (
                        <div className={styles['item']} key={index}>
                          <div className={styles['item-header']}>
                            {t['investigationReport.witness.title']}
                            {'    '}
                            {index >= 1 && index + 1}
                          </div>
                          <div className={styles['item-content']}>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.name']}
                                </div>
                                <div className={styles['value']}> {a.name}</div>
                              </div>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.role']}
                                </div>
                                <div className={styles['value']}>
                                  {
                                    a?.role.value[
                                      lang === 'en-US' ? 'en' : 'ar'
                                    ]
                                  }
                                </div>
                              </div>
                            </div>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.job']}
                                </div>
                                <div className={styles['value']}> {a.job}</div>
                              </div>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.nationality']}
                                </div>
                                <div className={styles['value']}>
                                  {
                                    a?.nationality.value[
                                      lang === 'en-US' ? 'en' : 'ar'
                                    ]
                                  }
                                </div>
                              </div>
                            </div>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.emiratesID']}
                                </div>
                                <div className={styles['value']}> {a.eid}</div>
                              </div>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.mobile']}
                                </div>
                                <div className={styles['value']}>
                                  {' '}
                                  {a.mobile}
                                </div>
                              </div>
                            </div>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.address']}
                                </div>
                                <div className={styles['value']}>
                                  {a.address}
                                </div>
                              </div>
                            </div>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.email']}
                                </div>
                                <div className={styles['value']}>
                                  {a.email || '--'}
                                </div>
                              </div>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.hiringDate']}
                                </div>
                                <div className={styles['value']}>
                                  {a.hiringDate || '--'}
                                </div>
                              </div>
                            </div>
                            {a?.attachment && a?.attachment.length > 0 && (
                              <Attachments srcList={a.attachment} />
                            )}
                            {/* Question */}
                            {a?.questions &&
                              a?.questions.map((b, bIndex) => (
                                <div key={bIndex}>
                                  <div className={styles['item-hr']}>
                                    <div className={styles['line']}></div>
                                  </div>
                                  <div className={styles['row']}>
                                    <div className={styles['col']}>
                                      <div className={styles['label']}>
                                        {
                                          t[
                                            'investigationReport.witness.question'
                                          ]
                                        }
                                        {'    '}
                                        {bIndex + 1}
                                      </div>
                                      <div className={styles['value']}>
                                        {b?.question}
                                      </div>
                                    </div>
                                  </div>
                                  <div className={styles['row']}>
                                    <div className={styles['col']}>
                                      <div className={styles['label']}>
                                        {
                                          t[
                                            'investigationReport.witness.answer'
                                          ]
                                        }
                                        {'    '}
                                        {bIndex + 1}
                                      </div>
                                      <div className={styles['value']}>
                                        {b?.answer}
                                      </div>
                                    </div>
                                  </div>
                                  {b?.attachment.length > 0 && (
                                    <Attachments srcList={b.attachment} />
                                  )}
                                </div>
                              ))}
                            <div className={styles['item-hr']}>
                              <div className={styles['line']}></div>
                            </div>
                            <Signtures signatures={a?.signatures} mode={0} />
                            {/* Witness / violator? */}
                            <div className={styles['item-hr']}>
                              <div className={styles['line']}></div>
                            </div>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.WitnessName']}
                                </div>
                                <div className={styles['value']}>{a.name}</div>
                              </div>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.emiratesID']}
                                </div>
                                <div className={styles['value']}>{a.eid}</div>
                              </div>
                            </div>
                            <div className={styles['row']}>
                              <div className={styles['col']}>
                                <div className={styles['label']}>
                                  {t['investigationReport.witness.pledge']}
                                </div>
                                <div className={styles['value']}>
                                  {t['investigationReport.witness.pledge.desc']}
                                </div>
                              </div>
                            </div>
                            <Signtures
                              signatures={[
                                {
                                  key: a.role.key,
                                  value: a.signature,
                                },
                              ]}
                              mode={1}
                            />
                          </div>
                        </div>
                      ))}

                    {/* Investigation Closure */}
                    <div className={styles['item']}>
                      <div className={styles['item-header']}>
                        {t['investigationReport.closure.title']}
                      </div>
                      <div className={styles['item-content']}>
                        <div className={styles['row']}>
                          <div className={styles['col']}>
                            <div className={styles['label']}>
                              {t['investigationReport.closure.closureSummary']}
                            </div>
                            <div className={styles['value']}>
                              {details?.closureSummary}
                            </div>
                          </div>
                        </div>
                        {details?.closureAction && (
                          <>
                            {details?.closureAction.map(
                              (a: string, index: number) => (
                                <div className={styles['row']} key={index}>
                                  <div className={styles['col']}>
                                    <div className={styles['label']}>
                                      {
                                        t[
                                          'investigationReport.closure.closureAction'
                                        ]
                                      }
                                      {'   '}
                                      {index + 1}
                                    </div>
                                    <div className={styles['value']}>{a}</div>
                                  </div>
                                </div>
                              )
                            )}
                          </>
                        )}
                      </div>
                    </div>
                  </div>
                </>
              ) : (
                <>
                  <div className={styles['history-empty']}>
                    <Empty description={t['empty.noData']} />
                  </div>
                </>
              )}
            </div>
          </Skeleton>
        </div>
      </Modal>
    </>
  );
}
export default InvestigationReport;
